package com.qiedan.controller;

import ch.qos.logback.classic.spi.IThrowableProxy;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.qiedan.bean.*;
import com.qiedan.service.AdminService;
import com.qiedan.service.ItemService;
import com.qiedan.service.OrdersService;
import com.qiedan.service.UserService;
import com.qiedan.utils.ChangeStatus;
import com.qiedan.utils.Consts;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;

@RestController
public class AdminController {
    @Autowired
    private AdminService adminService;
    @Autowired
    private ItemService itemService;
    @Autowired
    private OrdersService ordersService;
    @Autowired
    private UserService userService;

    /**
     * 用户登录
     */
    @RequestMapping(value = "/admin/login", method = RequestMethod.POST)
    public Object adminLogin(@RequestParam("name") String name, @RequestParam("password") String password, HttpSession session) {
        JSONObject jsonObject = new JSONObject();
        QueryWrapper<Admin> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("name", name).eq("password", password);
        Admin one = adminService.getOne(queryWrapper);
        if (one != null) {
            jsonObject.put(Consts.CODE, 1);
            jsonObject.put(Consts.MSG, "登录成功");
//            session.setAttribute("name",name);
            jsonObject.put("adminMsg", one);
            return jsonObject;
        }
        jsonObject.put(Consts.CODE, 0);
        jsonObject.put(Consts.MSG, "用户名或密码输错");
        return jsonObject;
    }

    /**
     * 管理员退出登录
     */
    @RequestMapping(value = "/admin/logout",method = RequestMethod.GET)
    public Object adminLogout(HttpSession session){
        session.removeAttribute("name");
        System.out.println("执行了请求");
        JSONObject jsonObject = new JSONObject();
        jsonObject.put(Consts.CODE,2);
        return jsonObject;
    }
    /**
     * 查询所有商品并展示
     */
    @RequestMapping(value = "/admin/selectItem",method = RequestMethod.GET)
    public Object selectItem(@RequestParam(value = "pn", defaultValue = "1") Integer pn){
        JSONObject jsonObject = new JSONObject();
        //分页查询数据
        Page<Item> itemPage = new Page<>(pn, 5);
        //分页查询结果
        Page<Item> page = itemService.page(itemPage, null);
        return page;
    }
    //商品更新图片
    @RequestMapping(value = "/admin/item_upload",method = RequestMethod.POST)
    public Object updateConsumerPic(@RequestParam("file") MultipartFile avatorFile, @RequestParam("id") Integer id) throws FileNotFoundException {
        JSONObject jsonObject = new JSONObject();
        System.out.println("----------------请求到上传请求");
        if (avatorFile.isEmpty()){
            jsonObject.put(Consts.CODE,0);
            jsonObject.put(Consts.MSG,"文件上传失败");
            return jsonObject;
        }
        //文件名=当前时间到毫秒+原来的名字
        String fileName = System.currentTimeMillis()+avatorFile.getOriginalFilename();
        //文件路径
        String filePath = "E:/gg/origin-of-khitan/itemImg";
        System.out.println("文件路径："+filePath);
        //如果文件 不存在，新增该路径
        File file1 = new File(filePath);
        if (!file1.exists()){

            file1.mkdir();
            System.out.println("创建了");
        }
        //实际的文件地址
        File dest = new File(filePath+System.getProperty("file.separator")+fileName);
        //存储到数据库里的相对文件地址
        String storeItemPath = "/itemImg/"+fileName;
        Item byId = itemService.getById(id);
        byId.setPhoto(storeItemPath);
        itemService.updateById(byId);
        System.out.println("----------------请求到上传请求");
        try {
            avatorFile.transferTo(dest);
            jsonObject.put("fileName",storeItemPath);
            return jsonObject;
        } catch (IOException e) {
            System.out.println("----------------抛出异常"+e);
            jsonObject.put(Consts.CODE,0);
            jsonObject.put(Consts.MSG,"上传失败"+e.getMessage());
        }finally {
            return jsonObject;
        }
    }
    //添加一个商品
    @RequestMapping(value = "/admin/addItem", method = RequestMethod.POST)
    public Object addItem(@RequestBody Item item) {
        boolean save = itemService.save(item);
        return save;
    }
    //删除一个商品
    @RequestMapping(value = "/admin/deleteItem",method = RequestMethod.GET)
    public Object deleteItem(@RequestParam("id")Integer id){
        return itemService.removeById(id);
    }
    //根据输入商品名字查找物品
    @RequestMapping(value = "/admin/selectLikeItem",method = RequestMethod.GET)
    public Object selectLikeItem(@RequestParam("name")String name){
        return itemService.list(new QueryWrapper<Item>().like("name",name));
    }

    /**
     * 查询所有订单
     * @param pn
     * @return
     * @throws ParseException
     */
    @RequestMapping(value = "/admin/order_select" , method = RequestMethod.GET)
    public Object selectOrderByStatus(@RequestParam(value = "pn",defaultValue = "1") Integer pn) throws ParseException {
        JSONObject jsonObject = new JSONObject();
        //分页查询数据
        Page<Orders> hOrdersPage = new Page<>(pn, 8);
        //分页查询结果
        Page<Orders> page = ordersService.page(hOrdersPage,null);
        List<Orders> list = page.getRecords();
        List<OrderAdmin> orderAdmins = new ArrayList<>();
        for (int i = 0; i<list.size(); i++) {
            User user = userService.getOne(new QueryWrapper<User>().eq("uid",list.get(i).getUid()));//
            OrderAdmin orderAdmin = new OrderAdmin();
            orderAdmin.setOid(list.get(i).getOid());//订单编号
            orderAdmin.setUsername(user.getUsername());//
            orderAdmin.setCreateTime(list.get(i).getCreatetime());//时间
            orderAdmin.setAddress(list.get(i).getAddress()); //地址
            orderAdmin.setPrices(list.get(i).getPrices());//价格
            orderAdmin.setStatus(ChangeStatus.changOfString(list.get(i).getStatus()));//状态
            Item item = itemService.getById(list.get(i).getIid());
            orderAdmin.setItemName(item.getName());
            orderAdmin.setNumber(list.get(i).getNumber());
            orderAdmins.add(orderAdmin);

        }
        jsonObject.put("records",orderAdmins);
        jsonObject.put("size",page.getSize());
        jsonObject.put("total",page.getTotal());
        return jsonObject;
    }

    //删除一个订单
    @RequestMapping(value = "/admin/deleteOrder",method = RequestMethod.GET)
    public Object deleteOrder(@RequestParam("oid")Integer oid){
        return ordersService.removeById(oid);
    }
    //查询所有用户以及分页
    @RequestMapping(value = "/admin/allConsumer" , method = RequestMethod.GET)
    public Object allConsumer(@RequestParam(value = "pn",defaultValue = "1") Integer pn){
        //分页查询数据
        Page<User> consumerPage = new Page<>(pn, 8);
        //分页查询结果
        Page<User> page = userService.page(consumerPage, null);
        return page;
    }
    //根据用户名查询用户
    @RequestMapping(value = "/admin/selectConsumer" , method = RequestMethod.GET)
    public Object selectConsumer(@RequestParam(value = "username") String username){
        return userService.list(new QueryWrapper<User>().like("username",username));
    }

    /**
     * 用户统计 返回所有的列表
     *
     * @return
     */
    @RequestMapping(value = "/admin/countConsumer", method = RequestMethod.GET)
    public Object countUSer() {
        return userService.list();
    }
    /**
     * 商品统计 返回所有的列表
     *
     * @return
     */
    @RequestMapping(value = "/admin/countItems", method = RequestMethod.GET)
    public Object countItem() {
        return itemService.list();
    }
}
